package org.huel.backend.controller;

import org.huel.backend.domain.entity.User;
import org.huel.backend.service.UserService;
import org.huel.backend.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

@RestController
@CrossOrigin
public class AuthController {
    private static final Logger logger = LoggerFactory.getLogger(User.class);


    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtil jwtUtil;

    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody Map<String, String> loginRequest) {
        String studentId = loginRequest.get("studentId");
        String password = loginRequest.get("password");


            System.out.println("收到登录请求: studentId=" + studentId);
            UserDetails userDetails = new org.springframework.security.core.userdetails.User(
                    studentId != null ? studentId : "default_user",
                    "password",
                    Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER"))
            );

            final String jwt = jwtUtil.generateToken(userDetails);

            // 创建默认用户信息或尝试获取实际用户信息
            User user;
            user = userService.getUserByStudentId(studentId);
            // 创建响应
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);

            Map<String, Object> userData = new HashMap<>();
            userData.put("id", user.getId());
            userData.put("studentId", user.getStudentId());
            userData.put("userName", user.getUserName());
            userData.put("address", user.getAddress());
            userData.put("classId", user.getClassId());
            userData.put("token", jwt);

            response.put("data", userData);
            response.put("message", "登录成功 (开发模式)");

            System.out.println("登录成功，用户: " + studentId);
            System.out.println(userData);

            return ResponseEntity.ok(response);

    }
    @PostMapping("/register")
    public ResponseEntity<?> register(@RequestBody User request) {
        Map<String, Object> response = new HashMap<>();

        try {
            logger.info("收到注册请求: studentId={}, classId={}", request.getStudentId(), request.getClassId());

            // 参数检验
            if (request.getStudentId() == null || request.getStudentId().trim().isEmpty()) {
                response.put("code", 400);
                response.put("message", "学号不能为空");
                return ResponseEntity.ok(response);
            }

            if (request.getPassword() == null || request.getPassword().trim().isEmpty()) {
                response.put("code", 400);
                response.put("message", "密码不能为空");
                return ResponseEntity.ok(response);
            }

            if (request.getClassId() == null || request.getClassId().trim().isEmpty()) {
                response.put("code", 400);
                response.put("message", "班级号不能为空");
                return ResponseEntity.ok(response);
            }

            // 如果用户名为空，设置为学号
            if (request.getUserName() == null || request.getUserName().trim().isEmpty()) {
                request.setUserName(request.getStudentId());
            }

            // 注册用户
            User user = userService.register(request);
            logger.info("用户注册成功: studentId={}, id={}", request.getStudentId(), user.getId());

            // 成功响应
            response.put("code", 200);
            response.put("message", "注册成功");
            response.put("data", user);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("注册失败: " + e.getMessage(), e);

            // 处理特定异常
            if (e.getMessage().contains("已被注册")) {
                response.put("code", 400);
                response.put("message", e.getMessage());
            } else {
                response.put("code", 500);
                response.put("message", "注册失败: " + e.getMessage());
            }

            return ResponseEntity.ok(response);
        }
    }

    // 检查学号是否可用的接口
    @GetMapping("/register/check/{studentId}")
    public ResponseEntity<?> checkStudentId(@PathVariable String studentId) {
        Map<String, Object> response = new HashMap<>();

        try {
            boolean exists = userService.checkStudentIdExists(studentId);

            response.put("code", 200);
            response.put("available", !exists);
            response.put("message", exists ? "该学号已被注册" : "该学号可用");

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("检查学号失败: " + e.getMessage(), e);
            response.put("code", 500);
            response.put("message", "检查学号失败: " + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }
}
